package com.efeichong.common.domain;

import com.efeichong.enums.ResultEnum;
import com.efeichong.util.EntityUtils;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import org.springframework.validation.BindingResult;

import java.io.Serializable;

/**
 * @author lxk
 * @date 2020/9/8
 * @description 统一返回
 */
@Data
@ApiModel
public class ResponseData<T> implements Serializable {

    private static final long serialVersionUID = 4338293435526973422L;

    private int status = ResultEnum.SUCCESS.getStatus();

    private String message = ResultEnum.SUCCESS.getMessage();

    private T data;

    public ResponseData() {

    }

    public ResponseData(T data) {
        this.data = data;
    }

    private ResponseData(ResultEnum resultEnum) {
        this.status = resultEnum.getStatus();
        this.message = resultEnum.getMessage();

    }

    public ResponseData(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public ResponseData(int status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public static ResponseData success() {
        return new ResponseData();
    }

    public static ResponseData success(Object data) {
        return new ResponseData(data);
    }

    public static ResponseData failure() {
        return new ResponseData(ResultEnum.FAILED);
    }

    public static ResponseData failure(String message) {
        return new ResponseData(ResultEnum.FAILED.getStatus(), message);
    }

    public static ResponseData loginExpire() {
        return new ResponseData(ResultEnum.LOGIN_EXPIRED);
    }

    public static ResponseData validResult(BindingResult result) {
        String defaultMessage = result.getAllErrors().get(0).getDefaultMessage();
        if (EntityUtils.isEmpty(defaultMessage)) {
            return new ResponseData();
        } else {
            return new ResponseData(ResultEnum.FAILED.getStatus(), defaultMessage);
        }
    }

    public ResponseData<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public ResponseData<T> setData(T data) {
        this.data = data;
        return this;
    }
}

